package com.msy.sign;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.web3j.crypto.*;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.http.HttpService;
import org.web3j.utils.Numeric;

import java.math.BigInteger;
import java.security.SignatureException;
import java.util.Arrays;

/**
 * @ClassName SignDemo
 * @Description TODO
 * @Author 13683
 * @Date 2019/8/20 10:22
 * @Version 1.0
 **/
public class SignDemo implements Runnable{
    private static final Logger log = LoggerFactory.getLogger(SignDemo.class);

    /**
     * 签名方法
     * @throws Exception
     */
    @Override
    public void run(){

        String PRIVATE_KEY_STRING =
                "a392604efc2fad9c0b3da43b5f698a2e3f270f170d859912be0d54742275c5f6";
        String PUBLIC_KEY_STRING =
                "0x506bc1dc099358e5137292f4efdd57e400f29ba5132aa5d12b18dac1c1f6aab"
                        + "a645c0b7b58158babbfa6c6cd5a48aa7340a8749176b120e8516216787a13dc76";
        String address = "0xef678007d18427e6022059dbc264f27507cd1ffc";

        BigInteger PRIVATE_KEY = Numeric.toBigInt(PRIVATE_KEY_STRING);
        BigInteger PUBLIC_KEY = Numeric.toBigInt(PUBLIC_KEY_STRING);
        ECKeyPair KEY_PAIR = new ECKeyPair(PRIVATE_KEY, PUBLIC_KEY);

        Credentials credentials = Credentials.create(KEY_PAIR);


        String message = "A test message";
        byte[] TEST_MESSAGE = message.getBytes();

        Sign.SignatureData signatureData = Sign.signMessage(TEST_MESSAGE, credentials.getEcKeyPair(),true);


        try {
            BigInteger publicKey = Sign.signedMessageToKey(TEST_MESSAGE,signatureData);

            log.info("validate：" + PUBLIC_KEY.equals(publicKey));
        } catch (SignatureException e) {
            e.printStackTrace();
        }

//        log.info("validate: "+ RecoverAddressFromSignature(stringSign,address,message));
    }

    /**
     * 字节数组转16进制
     * @param src
     * @return
     */
    public static String bytes2Hex(byte[] src) {
        if (src == null || src.length <= 0) {
            return null;
        }

        char[] res = new char[src.length * 2];
        final char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        for (int i = 0, j = 0; i < src.length; i++) {
            res[j++] = hexDigits[src[i] >> 4 & 0x0f];
            res[j++] = hexDigits[src[i] & 0x0f];
        }

        return new String(res);
    }


    public static void main(String[] args) throws InterruptedException {
        System.out.println("主线程开始：" + System.currentTimeMillis());
        Runnable signDemo = new SignDemo();

        Thread signThread = new Thread(signDemo);

        signThread.start();
        signThread.join();

        System.out.println("主线程结束：" + System.currentTimeMillis());

    }
}
